package com.weiai.wedding.service.cases;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.weiai.wedding.dao.cases.CasesDao;
import com.weiai.wedding.dao.cases.CasesExpDao;
import com.weiai.wedding.service.ShiroDbRealm;
import com.weiai.wedding.util.ConUtils;
import com.weiai.wedding.util.Constants;
import com.weiai.wedding.util.Pagination;
import com.weiai.wedding.dao.cases.CasesContentDao;
import  com.weiai.wedding.entity.cases.Cases;
import com.weiai.wedding.entity.cases.CasesContInfo;
import com.weiai.wedding.entity.cases.CasesContent;
import com.weiai.wedding.entity.cases.Resources;
import com.weiai.wedding.entity.cases.SmilAssember;
import sun.misc.BASE64Encoder;
/**
 * 彩信Service
 * @author xushunxin
 *
 */
@Component
@Transactional(readOnly=true)
public class CasesService {
	
	@Autowired
	private CasesDao casesDao;
	@Autowired
	private CasesExpDao casesExpDao;
	@Autowired
	private ShiroDbRealm shiroRealm;
	@Autowired
	private CasesContentDao casesContentDao;
	@Autowired
	private ResourcesService resourcesService;
	/**
	 * 无条件查询
	 * @return
	 */
//	public List<Cases> getAll(){
//		return CasesDao.findAllList();
//	}
	public Page<Cases> getAll(Pageable pager){
		return casesDao.findAllList(pager);
	}
	/**
	 * 根据查询条件查询
	 * @param Cases
	 * @return
	 */
	public Pagination<Cases> findList(Cases cases,Pagination page){
		Pagination<Cases> Pagination = casesExpDao.findList(cases.getCasesName(), cases.getCasesTitle(),page);
		
		return Pagination;
	}
	/**
	 * 根据查询条件查询
	 * @param Cases
	 * @return
	 */
	public Pagination<Cases> findCasesList(Cases cases,Pagination page){
		Pagination<Cases> Pagination = casesExpDao.findListByStatus(cases.getCasesName(), cases.getCasesTitle(),page);
		
		return Pagination;
	}
	
	/**
	 * 保存彩信信息
	 * @param Cases
	 */
	
	@Transactional(readOnly = false)
	public void save(Cases cases,String fileName,InputStream inputStream){
		String path = Constants.DIR+File.separator+Constants.RESOURCES
				+File.separator+ConUtils.formatDate(new Date(),"yyMMdd")
				+File.separator;
			ConUtils.createFileForInputStream(path, fileName, inputStream);
			cases.setResourcesDir(path+fileName);
		
		List<CasesContInfo> casesInfoList = cases.getCasesInfoList();
		combCont(casesInfoList, cases);
		cases.setCreateBy(ConUtils.getUser().getLoginName());
		cases.setCreateDate(ConUtils.getDate());
		cases.setStatus("S");//待审核状态
		casesDao.save(cases);
		shiroRealm.clearAllCachedAuthorizationInfo();
	}
	
	/**
	 * 修改
	 * @param Cases
	 */
	@Transactional(readOnly = false)
	public void update(Cases cases,String fileName,InputStream inputStream){
		String path = Constants.DIR+File.separator+Constants.RESOURCES
				+File.separator+ConUtils.formatDate(new Date(),"yyMMdd")
				+File.separator;
			ConUtils.createFileForInputStream(path, fileName, inputStream);
			cases.setResourcesDir(path+fileName);
		List<CasesContInfo> casesInfoList = cases.getCasesInfoList();
		//先删除已经存在的彩信内容信息
		this.deleteContent(cases);
		combCont(casesInfoList, cases);
		cases.setCreateDate(ConUtils.revDate(cases.getCreateDateStr(), "yyyy-MM-dd"));
		cases.setStatus("S");//待审核状态
		casesDao.save(cases);
		shiroRealm.clearAllCachedAuthorizationInfo();
	}
	
	/**
	 *审核
	 * @param Cases
	 */
	@Transactional(readOnly = false)
	public void audit(Long id,String auditDesc,String auditType){
		Cases cases = casesDao.findOne(id);
		cases.setAuditDesc(auditDesc);
		if(auditType.equals("1")&&"WaDEL".equals(cases.getStatus())){
			//删除审核通过
			cases.setStatus("X");
		}else
		if(auditType.equals("1")){
			//审核通过
			cases.setStatus("A");
		}
		if(auditType.equals("2")&&"WaDEL".equals(cases.getStatus())){
			cases.setStatus("A");
		}else if(auditType.equals("2")){
			//驳回状态
			cases.setStatus("R");
		}
		casesDao.save(cases);
		shiroRealm.clearAllCachedAuthorizationInfo();
	}
	
	/**
	 * 删除已经存在的彩信内容信息
	 * @param Cases
	 */
	private void deleteContent(Cases cases){
		List<CasesContent> list = casesContentDao.findCasesContentListByCasesId(cases);
		casesContentDao.delete(list);
	}
	/**
	 * 预览彩信内容
	 * @param id 彩信ID
	 * @return
	 */
	public Cases findCasesById(Long id){
		//查询主彩信表信息
		Cases cases = casesDao.findOne(id);
		//根据帧号和彩信ID进行分组查询。查询出根据帧数分组的彩信列表信息
		List list = casesContentDao.findCasesContentGroupByFrame(cases);
		List<CasesContInfo> casesInfoList = new ArrayList<CasesContInfo>();
		if(list!=null && list.size()>0){
			for(int i=0;i<list.size();i++){
				Object[] obj = (Object[]) list.get(i);
				Long framenum = (Long) obj[1];
				//根据帧号，彩信ID,资源类型进行组装彩信内容
				CasesContent txtCasesContent = casesContentDao.
					findCasesContentByFrameAndType(cases, framenum, Constants.RES_TYPE_TXT);
				CasesContent imgCasesContent = casesContentDao.
					findCasesContentByFrameAndType(cases, framenum, Constants.RES_TYPE_IMG);
				CasesContInfo info = new CasesContInfo();
				info.setCasesFramenum(framenum.toString());
				if(txtCasesContent!=null){
					info.setTxtCasesContent(txtCasesContent);
				}
				if(imgCasesContent!=null){
					info.setImgCasesContent(imgCasesContent);
				}
				casesInfoList.add(info);
			}
		}
		cases.setCasesInfoList(casesInfoList);
		return cases;
	}
	
	/**
	 * 查询彩信内容详细信息
	 * @param id
	 * @return
	 */
	public CasesContent findCasesContentById(Long id){
		
		return casesContentDao.findOne(id);
	}
	
	/**
	 * 校验彩信内容大小
	 * @param Cases
	 * @return
	 */
	public boolean checkFilesize(Cases cases){
//		Long countSize = 0l;
//		List<CasesContInfo> casesInfoList = cases.getCasesInfoList();
//		if(casesInfoList!=null && casesInfoList.size()>0){
//			for(CasesContInfo info:casesInfoList){
//				if(info!=null){
//					CasesContent imgCasesContent = info.getImgCasesContent();
//					if(imgCasesContent!=null){
//						if(imgCasesContent.getResourcesId()==null || "".equals(imgCasesContent.getResourcesId())){
//							MultipartFile file = imgCasesContent.getFile();
//							countSize=+file.getSize();
//						}else{
//							//上传文件中选择
//							Long id = imgCasesContent.getResourcesId();
//							Resources resources = resourcesService.getResources(id);
//							String filePath = resources.getResourcesDir();
//							File file = new File(filePath);
//							if(file!=null)
//								countSize+=file.length();
//						}
//						
//					}
//					CasesContent txtCasesContent = info.getTxtCasesContent();
//					if(txtCasesContent!=null){
//						byte[] by = txtCasesContent.getResContent();
//						countSize+=by.length;
//					}
//				}
//			}
//		}
		//if(countSize>Constants.FILE_SIZE)
			//return true;
		return false;
	}
	
	/**
	 * 组装彩信内容列表
	 * @param CasesInfoList
	 */
	@SuppressWarnings("restriction")
	private void combCont(List<CasesContInfo> casesInfoList,Cases cases){
		//SmilAssember smilAssember = new SmilAssember();
		int fileCount=0;
		String name = "att";
		if(casesInfoList!=null && casesInfoList.size()>0){
			for(CasesContInfo info:casesInfoList){
				if(info!=null){
					String casesFramenum = info.getCasesFramenum();
					CasesContent imgCasesContent = info.getImgCasesContent();
					CasesContent txtCasesContent = info.getTxtCasesContent();
					if(imgCasesContent!=null){
						imgCasesContent.setCasesFramenum(new Long(casesFramenum));//设置帧号
						//String filehzm = "";
						//String encode = "";
						//BASE64Encoder base = new BASE64Encoder();
						if(imgCasesContent.getResourcesId()==null || "".equals(imgCasesContent.getResourcesId())){
							MultipartFile file = imgCasesContent.getFile();
//							try {
//								encode = base.encode(file.getBytes());
//							} catch (IOException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
							//String fn = file.getOriginalFilename();
							///filehzm = fn.substring(fn.lastIndexOf("."), fn.length());
							Resources resource = this.saveResource(cases, file);
							imgCasesContent.setResourcesId(resource.getResourcesId());
						}else{
							//上传文件中选择
							//Long id = imgCasesContent.getResourcesId();
							//Resources resources = resourcesService.getResources(id);
							//String filePath = resources.getResourcesDir();
//							if(resources!=null){
//								try {
//									encode = base.encode(ConUtils.getBytesFromFile(new File(filePath)));
//								} catch (IOException e) {
//									// TODO Auto-generated catch block
//									e.printStackTrace();
//								}
//							}
							//filehzm = filePath.substring(filePath.lastIndexOf("."), filePath.length());
						}
						//imgCasesContent.setResContent(encode.getBytes());
						//String fileName = name+fileCount+filehzm;
						//imgCasesContent.setFileName(fileName);
						//smilAssember.addImg(fileName);
						fileCount++;
						cases.addCasesContentList(imgCasesContent);
					}
					if(txtCasesContent!=null){
						//如果存在文本的话
						txtCasesContent.setCasesFramenum(new Long(casesFramenum));//设置帧号
						//String fileName = name+fileCount+".txt";
						//txtCasesContent.setFileName(fileName);
						//smilAssember.addTxt(fileName);
						fileCount++;
						cases.addCasesContentList(txtCasesContent);
					}
					//smilAssember.addPar();
				}
			}
		}
		//cases.setCasesSmil(smilAssember.getSmilbody());
	}
	
	
	
	/**
	 * 保存资源
	 * @param Cases
	 * @param file
	 */
	private Resources saveResource(Cases cases,MultipartFile file){
		Resources rs = new Resources();
		rs.setResourcesName(cases.getCasesName());
		rs.setResourcesDesc(cases.getCasesDesc());
		//rs.setResourcesType("2");//私有
		try {
			resourcesService.saveResources(rs,  ConUtils.formatDate(new Date(),"yyMMddHHmmss")+file.getOriginalFilename(), file.getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return rs;
	}
	
	/**
	 * 检查彩信是否在使用当中
	 * @param id
	 * @return
	 */
	public boolean checkDelete(Long id){
		return false;
	}
	
	
	/**
	 * 删除彩信内容，将彩信状态变更为X状态即为删除
	 * @param id
	 */
	@Transactional(readOnly=false)
	public void deleteCases(Long id){
		Cases cases = casesDao.findOne(id);
		if("S".equals(cases.getStatus())||"R".equals(cases.getStatus())){
			cases.setStatus("X");
		}
		if("A".equals(cases.getStatus())){
			cases.setStatus("WaDEL");
		}
		casesDao.save(cases);
		shiroRealm.clearAllCachedAuthorizationInfo();
	}
//	@Transactional(readOnly = false)
//	public void saveCases(Cases cases) {
//		// TODO Auto-generated method stub
//		List<CasesContent> casesContentList = cases.getCasesContentList();
//		creatSmil(casesContentList, cases);
//		cases.setCreateDate(ConUtils.getDate());
//		casesDao.save(cases);
//		shiroRealm.clearAllCachedAuthorizationInfo();
//	}
//	@SuppressWarnings("restriction")
//	private void creatSmil(List<CasesContent> CasesContentList, Cases Cases) {
//		SmilAssember smilAssember = new SmilAssember();
//		if(CasesContentList!=null && CasesContentList.size()>0){
//			List<CasesContent> mList=new ArrayList();
//			for(CasesContent info:CasesContentList){
//				if(info!=null){
//					if(info.getResType()!=null && "txt".equals(info.getResType())){
//						//如果存在文本的话
//						smilAssember.addTxt(info.getFileName());
//					}else{
//						smilAssember.addImg(info.getFileName());
//					}
//					info.setCases(Cases);
//					mList.add(info);
//					smilAssember.addPar();
//				}
//			}
//			Cases.setCasesContentList(mList);
//		}
//		Cases.setCasesSmil(smilAssember.getSmilbody());
//	}
	public List<Cases> findCasesList() {
		// TODO Auto-generated method stub
		return casesDao.findAllList();
	}
}
